package org.springblade.common.utils.autoid.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import org.springblade.common.utils.autoid.config.RedisService;
import org.springblade.common.utils.autoid.service.TokenService;
import org.springblade.core.log.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Jackey
 * @date 2021年08月18日 10:24 上午
 */
@Service
public class TokenServiceImpl implements TokenService {
	@Autowired
	private RedisService redisService;
	/**
	 * 创建token
	 *
	 * @return
	 */
	@Override
	public String createToken() {
		String str = RandomUtil.randomString(8);
		StringBuilder token = new StringBuilder();
		try{
			token.append("autoid:").append(str);
			redisService.setEx(token.toString(), token.toString(),10000L);
			boolean notEmpty = StrUtil.isNotEmpty(token.toString());
			if(notEmpty) {
				return token.toString();
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	/**
	 * 检验token
	 *
	 * @param request
	 * @return
	 */
	@Override
	public boolean checkToken(HttpServletRequest request){
		String token = request.getHeader("autoid");
		if(StrUtil.isBlank(token)) {// header中不存在token
			token = request.getParameter("autoid");
			if(StrUtil.isBlank(token)) {// parameter中也不存在token
				throw new ServiceException("非法参数");
			}
		}
		if(!redisService.exists(token)) {
			throw new ServiceException("重复操作");
		}
		boolean remove = redisService.remove(token);
		if(!remove) {
			throw new ServiceException("重复操作");
		}
		return true;
	}

}
